<?php


namespace app\utils;

use AlibabaCloud\Client\AlibabaCloud;
use app\lib\exception\AliyunApiException;
use think\Exception;

class AliyunSms
{
    public function sendSms($phone){
        $code = rand(100000, 999999);

        AlibabaCloud::accessKeyClient(env('aliyun.ak'),env('aliyun.sk'))
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            AlibabaCloud::rpc()
                ->product('Dysmsapi')
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' =>  [
                        'RegionId'      =>  "cn-hangzhou",
                        'PhoneNumbers'  =>  $phone,
                        'SignName'      =>  env('aliyun.smssignname'),
                        'TemplateCode'  =>  env('aliyun.templatecode'),
                        'TemplateParam' =>  "{\"code\":\"".$code."\"}",
                    ],
                ])
                ->request();
        }catch (Exception $e){
            throw new AliyunApiException($e->getMessage());
        }

        return $code;
    }

}